#include "client.h"

// 接收线程函数
void* receiver_thread(void *arg) {
    if (arg != NULL) {
        printf("接收线程参数错误\n");
        return NULL;
    }
    char buffer[BUFFER_SIZE];

    while (1) {
        ssize_t len = recv(ctx.sockfd, buffer, sizeof(buffer), 0);
        if (len <= 0) {
            if (len == 0) {
                printf("服务端断开连接\n");
            } else {
                perror("接收错误");
            }
            pthread_mutex_lock(&ctx.mutex);
            close(ctx.sockfd);
            ctx.socket_closed = true;
            pthread_mutex_unlock(&ctx.mutex);
            pthread_exit(NULL);
        }

        pthread_mutex_lock(&ctx.mutex);
        ctx.response_length = len;
        memcpy(ctx.response, buffer, len);
        ctx.response_received = true;
        pthread_cond_signal(&ctx.cond);
        pthread_mutex_unlock(&ctx.mutex);
    }
    return NULL;
}
// 发送请求（带超时）
bool send_request(const char *request,const int request_length, char *response, int *response_length) {
    pthread_mutex_lock(&ctx.mutex);
    if (ctx.socket_closed) {
        printf("套接字已关闭，无法发送请求\n");
        pthread_mutex_unlock(&ctx.mutex);
        return false;
    }
    ctx.response_received = false;
    if (send(ctx.sockfd, request, request_length, 0) < 0) {
        perror("发送失败");
        pthread_mutex_unlock(&ctx.mutex);
        return false;
    }

    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_sec += TIMEOUT_SEC;

    int ret = 0;
    while (!ctx.response_received && ret == 0) {
        ret = pthread_cond_timedwait(&ctx.cond, &ctx.mutex, &ts);
    }

    if (ret != 0) {
        printf("请求超时: %s\n", request);
        pthread_mutex_unlock(&ctx.mutex);
        return false;
    }

    *response_length = ctx.response_length;
    memcpy(response, ctx.response, ctx.response_length);
    pthread_mutex_unlock(&ctx.mutex);
    return true;
}

// 心跳线程函数
void* heartbeat_thread(void *arg) {
    if (arg != NULL) {
        printf("心跳线程参数错误\n");
        return NULL;
    }
    sleep(1);
    while (1) {
        pthread_mutex_lock(&ctx.mutex);
        if (ctx.socket_closed) {
            pthread_mutex_unlock(&ctx.mutex);
            break;
        }
        if (send(ctx.sockfd, "HEARTBEAT", strlen("HEARTBEAT"), 0) < 0) {
            perror("发送心跳包失败");
            pthread_mutex_lock(&ctx.mutex);
            close(ctx.sockfd);
            ctx.socket_closed = true;
            pthread_mutex_unlock(&ctx.mutex);
            break;
        }
        pthread_mutex_unlock(&ctx.mutex);
        sleep(5); // 每 5 秒发送一次心跳包
    }
    return NULL;
}